package control

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"net/http"
)

type User struct {
	Username string `form:"username" json:"username" uri:"user" xml:"username" binding:"required"`
	Password string `form:"password" json:"password" uri:"password" xml:"password" binding:"required"`
}

//c.ShouldBindJSON(obj)  // 绑定解析json格式数据
//c.ShouldBind(obj) 或 c.Bind(obj)  //绑定解析form表单类型数据
//c.ShouldBindUri(obj)  //绑定解析uri路由参数数据
//还有 xml 数据等


func ParseJson(c *gin.Context){
	var user User
	if err:=c.ShouldBindJSON(&user);err!=nil{
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "error:"+err.Error(),
		})
		return
	}
	if user.Username != "go" || user.Password != "123456"{
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "用户名或密码错误",
		})
	}
	if user.Username == "go" && user.Password == "123456"{
		c.JSON(http.StatusOK, gin.H{
			"username":user.Username,
			"password":user.Password,
		})
		//安全的json，阻止json劫持
		c.SecureJSON(http.StatusOK, gin.H{
			"username":user.Username,
			"password":user.Password,
		})
		//或者
		user.Username="go"
		user.Password="123456"
		c.JSON(http.StatusOK,user)

		//xml数据
		c.XML(http.StatusOK, gin.H{
			"xml":"xml",
			"username":user.Username,
			"password":user.Password,
		})

		//yaml数据
		c.YAML(http.StatusOK, gin.H{
			"yaml":"yaml",
			"name":user.Username,
			"password":user.Password,
		})

		//protobuf格式
		//路由中
	}
}

func ParseForm(c *gin.Context){
    var user User
	// Bind()默认解析并绑定form格式,
	//可直接使用ShouldBind，根据请求头中content-type自动推断时json、form还是其他
    if err:=c.ShouldBind(&user);err!=nil{
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "error:"+err.Error(),
		})
		return
	}
	if user.Username != "go" || user.Password != "123456" {
		c.JSON(http.StatusBadRequest, gin.H{
			"status": http.StatusBadRequest,
			"msg": "用户名或密码错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"status": http.StatusOK,
		"username":user.Username,
		"password":user.Password,
		})
}

type formA struct {
	Foo string `json:"foo" xml:"foo" form:"foo" binding:"required"`
}

type formB struct {
	Bar string `json:"bar" xml:"bar" binding:"required"`
}

func SomeHandler(c *gin.Context) {
	objA := formA{}
	objB := formB{}
	// ShouldBind 使用了 c.Request.Body 不可重用
	if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil {
		c.JSON(http.StatusOK, `the body should be formA`)
		// 如果使用了ShouldBind，那么此时c.Request.Body就是EOF，即errB为EOF
		//使用ShouldBindBodyWith，
	} else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {
		c.JSON(http.StatusOK, `the body should be formB JSON`)
		//
	} else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil {
		c.JSON(http.StatusOK, `the body should be formB XML`)
	}
}